﻿using Android.App;
using Android.Content.Res;
using Android.OS;
using Android.Support.V4.App;
using Android.Support.V4.Widget;
using Android.Views;
using Android.Widget;
using Xamarin.ActionbarSherlockBinding.App;
using Cinemacenter.Shared;
using Android.Net;

namespace Cinemacenter.Droid
{
	[Activity (Label = "Cinemacenter", Icon = "@drawable/ic_launcher", ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
	[IntentFilter (new[] { Android.Content.Intent.ActionView }, Categories = new[] {
		Android.Content.Intent.CategoryBrowsable,
		Android.Content.Intent.CategoryDefault
	}, DataHost = "www.cinemacenter.com.ar", DataScheme = "http", DataPathPrefix = "/ficha/")]
	[IntentFilter (new[] { Android.Content.Intent.ActionView }, Categories = new[] {
		Android.Content.Intent.CategoryBrowsable,
		Android.Content.Intent.CategoryDefault
	}, DataHost = "www.cinemacenter.com.ar", DataScheme = "http", DataPathPrefix = "/ficham/")]
	public class MainActivity : SherlockFragmentActivity, CitiesFragment.ICitiesFragmentCallbacks, MarqueeFragment.IMarqueeFragmentCallbacks, UpcomingFragment.IUpcomingFragmentCallbacks
	{
		DrawerLayout _drawer;
		MyActionBarDrawerToggle _drawerToggle;
		ListView _drawerMainOptList;
		ListView _drawerSettings;
		LinearLayout _drawerLinear;

		string _drawerTitle;
		string _title;
		string[] _mainOptTitles;
		string[] _settingsTitles;
		SharedPreferenceManager sharedPref;

		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			SetContentView (Resource.Layout.Main);
			sharedPref = new SharedPreferenceManager (this);

			_title = _drawerTitle = Title;
			_mainOptTitles = Resources.GetStringArray (Resource.Array.OptArray);
			_settingsTitles = Resources.GetStringArray (Resource.Array.SettingsArray);
			_drawer = FindViewById<DrawerLayout> (Resource.Id.drawer_layout);
			_drawerMainOptList = FindViewById<ListView> (Resource.Id.left_drawer_mainopt);
			_drawerSettings = FindViewById<ListView> (Resource.Id.left_drawer_settings);

			_drawerLinear = FindViewById<LinearLayout> (Resource.Id.drawer_inside_layout);
			_drawer.SetDrawerShadow (Resource.Drawable.drawer_shadow_dark, (int)GravityFlags.Start);

			_drawerMainOptList.Adapter = new ArrayAdapter<string> (this, Resource.Layout.ViewDrawerMainItem, _mainOptTitles);
			_drawerMainOptList.ItemClick += (sender, args) => SelectMainOptItem (args.Position);

			_drawerSettings.Adapter = new DrawerAdapter (this, _settingsTitles);
			_drawerSettings.ItemClick += (sender, args) => SelectSettingsItem (args.Position);
		
			SupportActionBar.SetDisplayShowTitleEnabled (true);
			SupportActionBar.SetDisplayHomeAsUpEnabled (true);
	
			_drawerToggle = new MyActionBarDrawerToggle (this, _drawer,
				Resource.Drawable.ic_navigation_drawer,
				Resource.String.DrawerOpen,
				Resource.String.DrawerClose);

			_drawerToggle.DrawerClosed += (s, e) => {
				SupportActionBar.Title = _title;
				SupportInvalidateOptionsMenu ();
			};

			_drawerToggle.DrawerOpened += (s, e) => {
				SupportActionBar.Title = _drawerTitle;
				SupportInvalidateOptionsMenu ();
			};

			_drawer.SetDrawerListener (_drawerToggle);

			if (null == savedInstanceState) {
				if ((Intent.Data != null) && (Intent.Data.ToString ().ToLowerInvariant ().Contains ("/ficham/")))
					SelectMainOptItem (1);
				else
					SelectMainOptItem (0);
			}
		}

		void SelectMainOptItem (int position)
		{
			if ((sharedPref.CityId < 1) || (DBHelper.GetCities ().Count == 0)) {
				showCitiesDialog ();
			} else {
				UpdateTitle (position);
				Bundle arguments;
				Android.Support.V4.App.Fragment fragment;
				switch (position) {
				case 0:
					fragment = new MarqueeFragment ();
					arguments = new Bundle ();
					arguments.PutInt (MarqueeFragment.CityIdNumber, sharedPref.CityId);
					arguments.PutLong (MarqueeFragment.TsvtNumber, sharedPref.MarqueeTsvtPreference);
					break;
				case 1:
					fragment = new UpcomingFragment ();
					arguments = new Bundle ();
					arguments.PutInt (UpcomingFragment.CityIdNumber, sharedPref.CityId);
					arguments.PutLong (UpcomingFragment.TsvtNumber, sharedPref.UpcomingTsvtPreference);
					break;
				default:
					fragment = new MarqueeFragment ();
					arguments = new Bundle ();
					arguments.PutInt (MarqueeFragment.CityIdNumber, sharedPref.CityId);
					arguments.PutLong (MarqueeFragment.TsvtNumber, sharedPref.MarqueeTsvtPreference);
					break;
				}
				fragment.Arguments = arguments;
				var transaction = SupportFragmentManager.BeginTransaction ();
				transaction.SetCustomAnimations (Resource.Animation.fadein, Resource.Animation.fadeout, Resource.Animation.fadein, Resource.Animation.fadeout);
				transaction.Replace (Resource.Id.content_frame, fragment).CommitAllowingStateLoss ();
			}
			if (_drawer.IsDrawerOpen (_drawerLinear))
				_drawer.CloseDrawer (_drawerLinear);
		}

		void SelectSettingsItem (int position)
		{
			switch (position) {
			case 0:
				forceRefresh ();
				break;
			case 1:
				showCitiesDialog ();
				break;
			case 2:
				showAbout ();
				break;
			}
			if (_drawer.IsDrawerOpen (_drawerLinear))
				_drawer.CloseDrawer (_drawerLinear);
		}

		void showCitiesDialog ()
		{
			var fragment = CitiesFragment.Instance (sharedPref.CityId, sharedPref.CitiesTsvtPreference);				                
			fragment.ActivityCallbacks = this;
			var mFragmentTransaction = SupportFragmentManager.BeginTransaction ();
			mFragmentTransaction.Add (fragment, "CITIES_FRAGMENT");
			mFragmentTransaction.SetCustomAnimations (Resource.Animation.fadein, Resource.Animation.fadeout, Resource.Animation.fadein, Resource.Animation.fadeout);
			mFragmentTransaction.CommitAllowingStateLoss ();
		}

		void showAbout ()
		{
			var transaction = SupportFragmentManager.BeginTransaction ();
			transaction.SetCustomAnimations (Resource.Animation.fadein, Resource.Animation.fadeout, Resource.Animation.fadein, Resource.Animation.fadeout);
			var dialogFragment = new AboutFragment ();
			dialogFragment.Show (transaction, "ABOUT_DIALOG_FRAGMENT");
		}

		void UpdateTitle (int position)
		{
			_drawerMainOptList.SetItemChecked (position, true);
			SupportActionBar.Title = _title = _mainOptTitles [position];
			var cityId = sharedPref.CityId;
			foreach (var city in DBHelper.GetCities ()) {
				if (int.Parse (city.CityId) == cityId) {
					SupportActionBar.Subtitle = city.Name;
					return;
				}
			}
		}

		void forceRefresh ()
		{
			sharedPref.MarqueeTsvtPreference = long.MinValue;
			sharedPref.UpcomingTsvtPreference = long.MinValue;
			SelectMainOptItem (0);
		}

		protected override void OnPostCreate (Bundle savedInstanceState)
		{
			base.OnPostCreate (savedInstanceState);
			_drawerToggle.SyncState ();
		}

		public override void OnConfigurationChanged (Configuration newConfig)
		{
			base.OnConfigurationChanged (newConfig);
			_drawerToggle.OnConfigurationChanged (newConfig);
		}

		public override bool OnCreateOptionsMenu (Xamarin.ActionbarSherlockBinding.Views.IMenu menu)
		{
			SupportMenuInflater.Inflate (Resource.Menu.main, menu);
			return base.OnCreateOptionsMenu (menu);
		}

		public override bool OnOptionsItemSelected (Xamarin.ActionbarSherlockBinding.Views.IMenuItem item)
		{
			if (item.ItemId == Android.Resource.Id.Home) {
				ToogleDrawer ();
				return true;
			}
			return base.OnOptionsItemSelected (item);
		}

		void ToogleDrawer ()
		{
			if (_drawer.IsDrawerOpen (_drawerLinear)) {
				_drawer.CloseDrawer (_drawerLinear);
			} else {
				_drawer.OpenDrawer (_drawerLinear);
			}
		}

		public override bool OnKeyUp (Keycode keyCode, KeyEvent e)
		{
			if (keyCode == Keycode.Menu) {
				ToogleDrawer ();
				return true;
			} else if ((keyCode == Keycode.Back) && _drawer.IsDrawerOpen (_drawerLinear)) {
				_drawer.CloseDrawer (_drawerLinear);
				return true;
			} else
				return base.OnKeyUp (keyCode, e);
		}

		#region ICitiesFragmentCallbacks implementation

		public void NotifyOnCityChanged (int locationId)
		{
			var fr = (CitiesFragment)SupportFragmentManager.FindFragmentByTag ("CITIES_FRAGMENT");
			if (fr != null)
				SupportFragmentManager.BeginTransaction ().Remove (fr).CommitAllowingStateLoss ();
			sharedPref.CityId = locationId;
			forceRefresh ();
		}

		public void NotifyOnCitiesLoaded (CityCollection cities)
		{
			sharedPref.CitiesTsvtPreference = cities.Tsvt;
		}

		public void NotifyOnCitiesLoadFailed ()
		{
			var fr = (CitiesFragment)SupportFragmentManager.FindFragmentByTag ("CITIES_FRAGMENT");
			if (fr != null)
				SupportFragmentManager.BeginTransaction ().Remove (fr).CommitAllowingStateLoss ();
			Toast.MakeText (ApplicationContext, GetString (Resource.String.connection_error2), ToastLength.Long).Show ();
			if (sharedPref.CityId < 1) {
				View empty = FindViewById (Resource.Id.emptyRecords);
				empty.Visibility = ViewStates.Visible;		
			}
		}

		public void NotifyOnCityUnchanged ()
		{
			var fr = (CitiesFragment)SupportFragmentManager.FindFragmentByTag ("CITIES_FRAGMENT");
			if (fr != null)
				SupportFragmentManager.BeginTransaction ().Remove (fr).CommitAllowingStateLoss ();
		}

		#endregion

		#region IMarqueeFragmentCallbacks implementation

		public void NotifyOnMarqueeLoaded (Marquee dataset)
		{
			sharedPref.MarqueeTsvtPreference = dataset.Tsvt;
			if (dataset.Movies.Count > 0)
				Toast.MakeText (this, GetString (Resource.String.load_completed), ToastLength.Long).Show ();
		}

		public void NotifyMarqueeHasItems (bool hasItems)
		{
			View empty = FindViewById (Resource.Id.emptyRecords);
			empty.Visibility = hasItems ? ViewStates.Invisible : ViewStates.Visible;		
		}

		public void NotifyOnMarqueeLoadFailed ()
		{
			Toast.MakeText (this, GetString (Resource.String.connection_error), ToastLength.Long).Show ();
		}

		#endregion

		#region IUpcomingFragmentCallbacks implementation

		public void NotifyOnUpcomingLoaded (UpcomingMovies dataset)
		{
			sharedPref.UpcomingTsvtPreference = dataset.Tsvt;
			if (dataset.Movies.Count > 0)
				Toast.MakeText (this, GetString (Resource.String.load_completed), ToastLength.Long).Show ();
		}

		public void NotifyOnUpcomingHasItems (bool hasItems)
		{
			View empty = FindViewById (Resource.Id.emptyRecords);
			empty.Visibility = hasItems ? ViewStates.Invisible : ViewStates.Visible;	
		}

		public void NotifyOnUpcomingLoadFailed ()
		{
			Toast.MakeText (this, GetString (Resource.String.connection_error), ToastLength.Long).Show ();
		}

		#endregion
	}
}

